﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace kwzx.Common
{
    public class FileTran
    {
        static string targetDir = System.Configuration.ConfigurationSettings.AppSettings["remotingFolder"];  //远程ftp文件目录
        static string localFolder = System.Configuration.ConfigurationSettings.AppSettings["localFolder"];  //要下载到的本地目录
        static string hostname = System.Configuration.ConfigurationSettings.AppSettings["ftpServer"];  //ftp服务器
        static string username = System.Configuration.ConfigurationSettings.AppSettings["user"];  //用户名
        static string password = System.Configuration.ConfigurationSettings.AppSettings["pwd"];   //密码
        static string port = "21";  //端口




        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileinfo">需要上传的文件</param>
        /// <param name="targetDir">目标路径</param>
        /// <param name="hostname">ftp地址</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        public static void SaveFile(FileInfo fileinfo, string serverFilename, string fileType)
        {
            //1. check target
            string target;
            if (targetDir.Trim() == "")
            {
                return;
            }

            string URI = "FTP://" + hostname + "/" + fileType + "/" + serverFilename;
            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

            //设置FTP命令 设置所要执行的FTP命令，
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;

            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using (FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }

                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
                finally
                {
                    fs.Close();
                }

            }

            ftp = null;
            //设置FTP命令
            //ftp = GetRequest(URI, username, password);
            //ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名

            //string strFileExtention = System.IO.Path.GetExtension(fileinfo.Name);
            //string path = DateTime.Now.ToString("yyyymmdd") + "_" + DateTime.Now.ToString("hh") + "_" + DateTime.Now.ToString("MM") + "_" + DateTime.Now.ToString("ss") + strFileExtention;
            //ftp.RenameTo = path;
            //serverFilename = path;
            //try
            //{
            //    ftp.GetResponse();
            //}
            //catch (Exception ex)
            //{
            //    ftp = GetRequest(URI, username, password);
            //    ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
            //    ftp.GetResponse();
            //    throw ex;
            //}
            //finally
            //{
            //    //fileinfo.Delete();
            //}

            // 可以记录一个日志  "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
            ftp = null;

            #region
            /*****
             *FtpWebResponse
             * ****/
            //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse();
            #endregion
        }





        #region  多端口
        /// <summary>
        /// ftp文件上传 用于scm
        /// </summary>
        /// <param name="fileinfo">上传的文件流</param>
        /// <param name="serverFilename">文件名称</param>
        /// <param name="ftppath">ftp文件路径</param>
        /// <param name="port">端口</param>
        public static void SaveFile(FileInfo fileinfo, string serverFilename, string ftppath, int port)
        {
            //1. check target
            FtpCheckDirectoryExist(ftppath,port);

            string URI = "FTP://" + hostname + ":" + port + "/" + ftppath + "/" + serverFilename;
            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

            //设置FTP命令 设置所要执行的FTP命令，
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;

            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using (FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }

                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
                finally
                {
                    fs.Close();
                }

            }

            ftp = null;

            // 可以记录一个日志  "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
            ftp = null;

            #region
            /*****
             *FtpWebResponse
             * ****/
            //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse();
            #endregion
        }



        //判断文件的目录是否存,不存则创建   
        public static void FtpCheckDirectoryExist(string destFilePath, int port)
        {
            //  string fullDir = FtpParseDirectory(destFilePath);
            string[] dirs = destFilePath.Split('/');
            string curDir = "/";
            for (int i = 0; i < dirs.Length; i++)
            {
                string dir = dirs[i];
                //如果是以/开始的路径,第一个为空     
                if (dir != null && dir.Length > 0)
                {
                    try
                    {
                        curDir += dir + "/";
                        FtpMakeDir(curDir,port);
                    }
                    catch (Exception)
                    { }
                }
            }
        }

        //public static string FtpParseDirectory(string destFilePath)
        //{
        //    return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));
        //}

        //创建目录   
        public static Boolean FtpMakeDir(string localFile, int port)
        {
            string URI = "FTP://" + hostname + ":" + port + "/" + localFile;

            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(URI);
            req.Credentials = new NetworkCredential(username, password);
            req.Method = WebRequestMethods.Ftp.MakeDirectory;
            try
            {
                FtpWebResponse response = (FtpWebResponse)req.GetResponse();
                response.Close();
            }
            catch (Exception)
            {
                req.Abort();
                return false;
            }
            req.Abort();
            return true;
        }



        #endregion







        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileinfo">需要上传的文件</param>
        /// <param name="targetDir">目标路径</param>
        /// <param name="hostname">ftp地址</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        public static int SaveFile(FileInfo fileinfo, string serverFilename, string fileType, string temp)
        {
            //1. check target
            string target;
            if (targetDir.Trim() == "")
            {
                return -2;
            }

            string URI = "FTP://" + hostname + ":21/" + fileType + "/" + serverFilename;
            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

            //设置FTP命令 设置所要执行的FTP命令，
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;

            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using (FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                        return 0;//上传成功
                    }

                }
                catch (Exception ex)
                {
                    ex.ToString();
                    return -1;//上传失败
                }
                finally
                {
                    fs.Close();
                }

            }

            ftp = null;
            //设置FTP命令
            //ftp = GetRequest(URI, username, password);
            //ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名

            //string strFileExtention = System.IO.Path.GetExtension(fileinfo.Name);
            //string path = DateTime.Now.ToString("yyyymmdd") + "_" + DateTime.Now.ToString("hh") + "_" + DateTime.Now.ToString("MM") + "_" + DateTime.Now.ToString("ss") + strFileExtention;
            //ftp.RenameTo = path;
            //serverFilename = path;
            //try
            //{
            //    ftp.GetResponse();
            //}
            //catch (Exception ex)
            //{
            //    ftp = GetRequest(URI, username, password);
            //    ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
            //    ftp.GetResponse();
            //    throw ex;
            //}
            //finally
            //{
            //    //fileinfo.Delete();
            //}

            // 可以记录一个日志  "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
            ftp = null;

            #region
            /*****
             *FtpWebResponse
             * ****/
            //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse();
            #endregion
        }









        /// <summary>
        /// ftp上传
        /// </summary>
        /// <param name="fileinfo">文件</param>
        /// <param name="serverFilename">目标名称</param>
        /// <param name="ftpPath">ftp地址</param>
        public static void UploadFile(FileInfo fileinfo, string serverFilename, string ftpPath)
        {
            //car//2013/05/03/
            //1. check target
            FtpCheckDirectoryExist(ftpPath);

            string target;
            if (targetDir.Trim() == "")
            {
                return;
            }
            target = Guid.NewGuid().ToString();  //使用临时文件名


            string URI = "FTP://" + hostname + "/" + ftpPath + "/" + serverFilename;
            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

            //设置FTP命令 设置所要执行的FTP命令，
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;

            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using (FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }

                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
                finally
                {
                    fs.Close();
                }

            }

            ftp = null;
            //设置FTP命令
            //ftp = GetRequest(URI, username, password);
            //ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名

            //string strFileExtention = System.IO.Path.GetExtension(fileinfo.Name);
            //string path = DateTime.Now.ToString("yyyymmdd") + "_" + DateTime.Now.ToString("hh") + "_" + DateTime.Now.ToString("MM") + "_" + DateTime.Now.ToString("ss") + strFileExtention;
            //ftp.RenameTo = path;
            //serverFilename = path;
            //try
            //{
            //    ftp.GetResponse();
            //}
            //catch (Exception ex)
            //{
            //    ftp = GetRequest(URI, username, password);
            //    ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
            //    ftp.GetResponse();
            //    throw ex;
            //}
            //finally
            //{
            //    //fileinfo.Delete();
            //}

            // 可以记录一个日志  "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
            ftp = null;


        }

        private static FtpWebRequest GetRequest(string URI, string username, string password)
        {
            //根据服务器信息FtpWebRequest创建类的对象
            FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
            //提供身份验证信息
            result.Credentials = new System.Net.NetworkCredential(username, password);
            //设置请求完成之后是否保持到FTP服务器的控制连接，默认值为true
            result.KeepAlive = false;
            return result;
        }

        public static string wzplj()
        {
            string wzp = AppDomain.CurrentDomain.BaseDirectory + "\\无图片.jpg";

            return wzp;

        }

        /// <summary>
        /// ftp下载
        /// </summary>
        /// <param name="localDir">本地路径</param>
        /// <param name="zpname">要下载文件名</param>
        /// <param name="FtpFile">要下载的文件路径</param>
        /// <returns></returns>
        public static string DownloadFile(string localDir, string zpname, string FtpFile)
        {
            string URI = "FTP://" + hostname + "/" + FtpFile;
            //string tmpname = Guid.NewGuid().ToString();
            string localfile = localDir + zpname;

            if (!File.Exists(localfile))
            {
                System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
                ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
                ftp.UseBinary = true;
                ftp.UsePassive = false;
                try
                {
                    using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
                    {
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            //loop to read & write to file
                            using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
                            {
                                try
                                {
                                    byte[] buffer = new byte[2048];
                                    int read = 0;
                                    do
                                    {
                                        read = responseStream.Read(buffer, 0, buffer.Length);
                                        fs.Write(buffer, 0, read);
                                    } while (!(read == 0));
                                    responseStream.Close();
                                    fs.Flush();
                                    fs.Close();
                                }
                                catch (Exception)
                                {
                                    //catch error and delete file only partially downloaded
                                    fs.Close();
                                    //delete target file as it's incomplete
                                    File.Delete(localfile);
                                    throw;
                                }
                            }

                            responseStream.Close();
                        }

                        response.Close();
                    }
                }

                catch (Exception ex)
                {
                    localfile = wzplj();
                    //if (ex.ToString().Contains("550"))
                    //{
                    //    URI = "FTP://" + hostname + "/DBPersonImg/无图片.jpg";
                    //     tmpname = Guid.NewGuid().ToString();
                    //     localfile = localDir + tmpname;

                    //    ftp = GetRequest(URI, username, password);
                    //    ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
                    //    ftp.UseBinary = true;
                    //    ftp.UsePassive = false;
                    //    using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
                    //    {
                    //        using (Stream responseStream = response.GetResponseStream())
                    //        {
                    //            //loop to read & write to file
                    //            using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
                    //            {
                    //                try
                    //                {
                    //                    byte[] buffer = new byte[2048];
                    //                    int read = 0;
                    //                    do
                    //                    {
                    //                        read = responseStream.Read(buffer, 0, buffer.Length);
                    //                        fs.Write(buffer, 0, read);
                    //                    } while (!(read == 0));
                    //                    responseStream.Close();
                    //                    fs.Flush();
                    //                    fs.Close();
                    //                }
                    //                catch (Exception)
                    //                {
                    //                    //catch error and delete file only partially downloaded
                    //                    fs.Close();
                    //                    //delete target file as it's incomplete
                    //                    File.Delete(localfile);
                    //                    throw;
                    //                }
                    //            }

                    //            responseStream.Close();
                    //        }

                    //        response.Close();
                    //    }
                    //}
                }

                try
                {
                    ////    File.Delete(localDir + @"\" + FtpFile);
                    //int clentPath = FtpFile.LastIndexOf("/");
                    //string clientnewPath = FtpFile.Substring(clentPath, FtpFile.Length - clentPath);
                    //if (System.IO.File.Exists(localDir + clientnewPath))
                    //{
                    //    string lj = localDir + clientnewPath;
                    //    System.IO.File.Delete(lj);

                    //}
                    //File.Move(localfile, localDir + clientnewPath);
                    //// File.Copy(localfile, localDir + clientnewPath);
                    ////    ftp = null;
                    ////    ftp = GetRequest(URI, username, password);
                    ////    ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
                    ////    ftp.GetResponse();

                }
                catch (Exception ex)
                {
                    //    File.Delete(localfile);
                    // throw ex;
                }
                ftp = null;
            }
            else
            {


            }
            // 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." );

            return localfile;
        }


        /// <summary>
        /// 判断ftp服务器上该目录是否存在
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="ftpHostIP"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private bool ftpIsExistsFile(string dirName)
        {
            bool flag = true;
            try
            {

                string uri = "ftp://" + hostname + "/" + dirName;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.ListDirectory;

                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
            catch (Exception)
            {
                flag = false;
            }
            return flag;
        }

        //判断文件的目录是否存,不存则创建   
        public static void FtpCheckDirectoryExist(string destFilePath)
        {
            //  string fullDir = FtpParseDirectory(destFilePath);
            string[] dirs = destFilePath.Split('/');
            string curDir = "/";
            for (int i = 0; i < dirs.Length; i++)
            {
                string dir = dirs[i];
                //如果是以/开始的路径,第一个为空     
                if (dir != null && dir.Length > 0)
                {
                    try
                    {
                        curDir += dir + "/";
                        FtpMakeDir(curDir);
                    }
                    catch (Exception)
                    { }
                }
            }
        }

        //public static string FtpParseDirectory(string destFilePath)
        //{
        //    return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));
        //}

        //创建目录   
        public static Boolean FtpMakeDir(string localFile)
        {
            string URI = "FTP://" + hostname + "/" + localFile;

            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(URI);
            req.Credentials = new NetworkCredential(username, password);
            req.Method = WebRequestMethods.Ftp.MakeDirectory;
            try
            {
                FtpWebResponse response = (FtpWebResponse)req.GetResponse();
                response.Close();
            }
            catch (Exception)
            {
                req.Abort();
                return false;
            }
            req.Abort();
            return true;
        }








    }
}
